<?php
namespace app\index\controller;
use think\Db;
use think\Request;
use think\Controller;
use think\Exception;
// 指定允许其他域名访问
header('Access-Control-Allow-Origin:*');
// 响应类型
header('Access-Control-Allow-Methods:POST'); 
// 响应头设置
header('Access-Control-Allow-Headers:x-requested-with,content-type');
use app\index\model\CrmChannelCount;
use app\index\model\GoodsNext;
use app\index\model\Goods;
use app\index\server\Index;
class Screen extends Controller
{
    private $yingqiGao = 219;
    private $yingqiDi = 215;
    private $yingqiDay = "2023-10-21";
    private $yingqiTitle = "231020期";
    private $teacher = '';
    private $time = '';
    private $starttime = '';
    private $endtime = '';

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->initialization();
    }

    private function initialization(){
        $goods = Index::g_d_user_cache('get_screen_goods',md5('get_screen_goods'));
        if(empty($goods)){
            $goods=(new Goods())->where('search_type','in',[1,2,3])->where('time','<',time())->page(1)->limit(2)->order('time desc')->select();
            Index::set_user_cache('set_screen_goods',md5('get_screen_goods'),$goods);
        }
        $screen_s = Index::g_d_user_cache('get_screen',md5('get_screen'));
        if(empty($screen_s)){
            $screen_s = [];
            foreach ($goods as $value){
                if(strpos($value['title'],'D') !== false){
                    $screen_s['yingqiDi']=$value['id'];
                }
                if(strpos($value['title'],'G') !== false){
                    $screen_s['yingqiGao']=$value['id'];
                }
            }
            $screen_s['date']=$goods[0]['date'];
            $goods_next = (new GoodsNext())->where('goods_id','in',[$goods[0]['id'],$goods[1]['id']])->order('kaibo_time desc')->find();
            $kaibo_time = date("Y-m-d",$goods_next['kaibo_time']);
            $screen_s['yingqiDay']=$kaibo_time;
            $screen_s['yingqiTitle']=mb_substr($goods[0]['title'],0,6,"UTF-8").'期';
            //$teacher=array_unique(explode(' ',$goods[0]['name'].' '.$goods[1]['name']));
            $screen_s['teacher']=$goods[0]['name'];//implode(' ',$teacher);
            $screen_s['time']=$goods_next['desc'];
            $screen_s['starttime']=$goods_next['kaibo_time'];
            $endtime = explode('日',$goods_next['desc'])[1];
            $endtime = explode('--',$endtime);
            $screen_s['endtime']=strtotime($this->yingqiDay.' '.trim($endtime[0]).'-'.trim($endtime[1]));
            Index::set_user_cache('set_screen',md5('get_screen'),$screen_s);
        }else{
            $end = strtotime(date('Y-m-d',$goods[0]['time']).' 23:59:59');
            if($screen_s['date']!=$goods[0]['date'] && $end<time()){
                Index::g_d_user_cache('delete_screen',md5('get_screen'));
                Index::g_d_user_cache('delete_screen_goods',md5('get_screen_goods'));
            }
        }
        $this->yingqiGao=$screen_s['yingqiGao'];
        $this->yingqiDi=$screen_s['yingqiDi'];
        $this->yingqiDay=$screen_s['yingqiDay'];
        $this->yingqiTitle=$screen_s['yingqiTitle'];
        $this->teacher=$screen_s['teacher'];
        $this->time=$screen_s['time'];
        $this->starttime=$screen_s['starttime'];
        $this->endtime=$screen_s['endtime'];
    }

    // 顶部信息
    public function topInfo()
    {
        $datas['teacher'] = $this->teacher;
        $datas['platform'] = '保利威';
        $datas['time'] =$this->time;
        $datas['starttime'] =$this->starttime;
        $datas['endtime'] = $this->endtime;
        apiReturn(200,'获取成功',$datas);
    }

    // 高低年级数量
    public function numbers()
    {
        $yingqiGao = $this->yingqiGao;
        $yingqiDi = $this->yingqiDi;
        $where2['course_id'] = $yingqiGao;
        $where3['course_id'] = $yingqiDi;
        $gaoCountNumber = db('goods_phone')->where($where2)->count();
        $diCountNumber = db('goods_phone')->where($where3)->count();
        $datas = [
            'total'=>$gaoCountNumber+$diCountNumber,
            'list'=>[
                ['name'=>'小高','color'=>'#ef6567','number'=>$gaoCountNumber],
                ['name'=>'小低','color'=>'#5470c6','number'=>$diCountNumber]
            ],
            'color'=>['#ef6567','#5470c6']
        ];

        apiReturn(200,'获取成功',$datas);
    }

    // 营期总业绩
    public function benchCount()
    {
        $yingqiGao = $this->yingqiGao;
        $yingqiDi = $this->yingqiDi;
        $yingqiTitle = $this->yingqiTitle;
        $where1['course_id'] = ['in',$yingqiGao.','.$yingqiDi];
        $allCount = db('crm_yingqi_count')->where($where1)->count();
        $where2['course_id'] = $yingqiGao;
        $gaoCount = db('crm_yingqi_count')->where($where2)->count();
        $where3['course_id'] = $yingqiDi;
        $diCount = db('crm_yingqi_count')->where($where3)->count();
        $gaoCountNumber = db('goods_phone')->where($where2)->count();
        $diCountNumber = db('goods_phone')->where($where3)->count();
        $allCountNumber = $gaoCountNumber + $diCountNumber;

        apiReturn(200,'获取成功',['yingqiTitle'=>$yingqiTitle,'allCount'=>$allCount,'gaoCount'=>$gaoCount,'diCount'=>$diCount,'gaoCountNumber'=>$gaoCountNumber,'diCountNumber'=>$diCountNumber,'allCountNumber'=>$allCountNumber]);
    }

    // 分组排名
    public function fenzuPaihang()
    {
        $yingqiGao = $this->yingqiGao;
        $yingqiDi = $this->yingqiDi;
        $zuIds = [4,10,12,14];
        $zuList = [];
        $colorArray = array('#ef6567', '#5470c6', '#91cd77', '#fc8251', '#f9c956', '#75bedc', '#91cd77', '#ef6567');
        foreach ($zuIds as $key => $value) {
            $zuList[$key]['name'] = db('crm_fenzu')->where('id',$value)->value('name');
            $wherezu_id = $this->getFenzuList($value);
            $where['manage_id'] = $this->getManageList($wherezu_id);
            $where['course_id'] = ['in',$yingqiGao.','.$yingqiDi];
            $zuList[$key]['number'] = db('crm_yingqi_count')->where($where)->count();
            $zuList[$key]['color'] = $colorArray[$key];

            $where1['public_yingqi'] = ['in',$yingqiGao.','.$yingqiDi];
            $where1['manage_id'] = $where['manage_id'];
            $zuList[$key]['customer_number'] = db('crm_customer')->where($where1)->count();
            if ($zuList[$key]['customer_number'] <= $zuList[$key]['number']) {
                if (!empty($zuList[$key]['number'])) {
                    $zhuanhua = 100;
                    $zuList[$key]['customer_number'] = $zuList[$key]['number'];
                }else{
                   $zhuanhua = 0; 
                }
            }else{
                $zhuanhua = sprintf("%.2f", $zuList[$key]['number']/$zuList[$key]['customer_number']*100);
            }
            
            $zuList[$key]['zhuanhua'] = intval($zhuanhua*100);
        }
        //数组降序排列
        usort($zuList, function($a, $b) {
            return $b['zhuanhua']- $a['zhuanhua'];
        });
        apiReturn(200,'获取成功',$zuList);
    }

    // 组内排行
    public function fenzuCount()
    {
        try {
            $data['type'] = input('type');
            $yingqiGao = $this->yingqiGao;
            $yingqiDi = $this->yingqiDi;
            if ($data['type'] == 0) {
                $zuIds = [
                    ['id'=>0,'name'=>'全部']
                ];
            }elseif ($data['type'] == 1) {
                $zuIds = [
                    ['id'=>4,'name'=>'一部']
                ];
            }elseif ($data['type'] == 2) {
                $zuIds = [
                    ['id'=>10,'name'=>'二部'],
                ];
            }elseif ($data['type'] == 4) {
                $zuIds = [
                    ['id'=>12,'name'=>'四部']
                ];
            }else{
                $zuIds = [
                    ['id'=>14,'name'=>'七部']
                ];
            }
            // $zuIds = [
            //     ['id'=>4,'name'=>'一部'],
            //     ['id'=>10,'name'=>'二部'],
            //     ['id'=>12,'name'=>'四部'],
            //     ['id'=>14,'name'=>'七部']
            // ];
            $list = [];
            foreach ($zuIds as $key => $value) {
                $list[$key]['id'] = $value['id'];
                $list[$key]['name'] = $value['name'];
                if ($data['type'] != 0) {
                    $zuId = $value['id'];
                    $wherezu_id = $this->getFenzuList($zuId);
                    $where['a.manage_id'] = $this->getManageList($wherezu_id);
                }
                $where['a.course_id'] = ['in',$yingqiGao.','.$yingqiDi];
                $where1['public_yingqi'] = ['in',$yingqiGao.','.$yingqiDi];

                $list[$key]['zuPaihang'] = db('crm_yingqi_count')->alias('a')->join('tp_crm_manage b','a.manage_id=b.username')->field('a.manage_id,count(a.manage_id) as numbers,b.name as manage_name')->where($where)->group('a.manage_id')->order('numbers desc')->select();

                foreach ($list[$key]['zuPaihang'] as $key1 => &$value1) {
                    $where1['manage_id'] = $value1['manage_id'];
                    $value1['customer_number'] = db('crm_customer')->where($where1)->count();
                    if ($value1['customer_number'] <= $value1['numbers']) {
                        $value1['customer_number'] = $value1['numbers'];
                        $zhuanhua = 100;
                    }else{
                        $zhuanhua = sprintf("%.2f", $value1['numbers']/$value1['customer_number']*100);
                    }
                    
                    $value1['zhuanhua'] = intval($zhuanhua*100);
                }
            }
            $zuPaihang = $list[0]['zuPaihang'];
            //数组降序排列
            usort($zuPaihang, function($a, $b) {
                return $b['zhuanhua']- $a['zhuanhua'];
            });
            $list = [['id'=>$list[0]['id'],'name'=>$list[0]['name'],'zuPaihang'=>$zuPaihang]];
            apiReturn(200,'获取成功',$list);
        } catch (Exception $e) {
            apiReturn(201,$e->getMessage());
        }
    }

    // 时段业绩曲线
    public function minutesCount()
    {
        $yingqiDay = $this->yingqiDay;
        $minutesArray = ["20:00-20:10","20:10-20:20","20:20-20:30","20:30-20:40","20:40-20:50","20:50-21:00","21:00-21:10","21:10-21:20"];
        $startTime = strtotime($yingqiDay.' 20:00:00');
        $numbers = [];
        foreach ($minutesArray as $key => &$value) {
            $starttime1 = $startTime;
            $endtime1 = $starttime1+600;
            if ($key == 7) {
                $where['date'] = [['egt',$starttime1],['elt',$endtime1]];
            }else{
                $where['date'] = [['egt',$starttime1],['lt',$endtime1]];
            }
            $numbers[] = db('crm_yingqi_count')->where($where)->count();
            $startTime += 600; 
        }

        apiReturn(200,'获取成功',['time'=>implode(',', $minutesArray),'number'=>implode(',', $numbers)]);
    }

    // 获取工号分组列表
    public function getFenzuList($zu_id = null)
    {
        $whereid = '';
        $zu_info = db('crm_fenzu')->where('id',$zu_id)->find();
        if (empty($zu_info)) {
            apiReturn(201,'分组信息不存在');
        }
        if ($zu_info['pid'] == 0) {
            $next_zu_list = db('crm_fenzu')->where(array('pid'=>$zu_info['id']))->column('id');
            $zu_ids = [];
            $zu_ids[] = $zu_info['id'];
            foreach ($next_zu_list as $key2 => $value2) {
                $zu_ids[] = $value2;
            }
            $whereid = array('in',implode(',', $zu_ids));
        }else{
            $whereid = $zu_info['id'];
        }
        
        return $whereid;
    }

    // 获取工号分组列表
    public function getManageList($zu_id = null)
    {
        $whereusername = [];
        $where2['zu_id'] = $zu_id;
        $zuManageList = db('crm_manage')->where($where2)->column('username');
        $whereusername =  array('in',implode(',', $zuManageList));

        return $whereusername;
    }

    public function channel(){
        $goods_next_model = new  GoodsNext;
        $goods_next_di = $goods_next_model->where('goods_id',$this->yingqiDi)->field('id,title')->select();
        $goods_next_di = $this->arrange($goods_next_di);
        $goods_next_gao = $goods_next_model->where('goods_id',$this->yingqiGao)->field('id,title')->select();
        $goods_next_gao = $this->arrange($goods_next_gao,'小高');
        $data = array_merge($goods_next_di,$goods_next_gao);
        $list = [];
        if(count($data)==0){
            apiReturn(200,'成功',$data);
        }
        $list['color']=['red','green','blue','orange'];
        $list['date']=$data[0]['date_'];
        $titles=[];
        $series=[];
        foreach ($data as $k=>$value){
            array_push($titles,$value['title']);
            $serie= [
                'name'=>$value['title'],
                'type'=>'line',
                'smooth'=>true,
                'data'=>$value['count'],
                'lineStyle'=>[
                    'color'=> $list['color'][$k]
                ]
            ];
            array_push($series,$serie);
        }
        $list['title']=$titles;
        $list['series']=$series;
        apiReturn(200,'成功',$list);
    }

    private function arrange(&$goods_next,$type='小低'){
        $channel_model =new  CrmChannelCount;
        foreach ($goods_next as &$value){
            if (strpos($value['title'], '第一天') !== false) {
                $value['title']=$type.'第一天';
            }else{
                $value['title']=$type.'第二天';
            }
            $channel =  $channel_model->where('goods_next_id',$value['id'])->order('time asc')->select();
            $count = [];
            $date = [];
            foreach ($channel as $v){
                array_push($count,$v['count']);
                array_push($date,date('H:i',$v['time']));
            }
            $value['count']=$count;
            $value['date_']=$date;
        }
        return $goods_next;
    }
}
